import axios from 'axios'
import nProgress from 'nprogress'
import { ElMessage } from 'element-plus'
import * as Settings from '@/settings'
import { getToken } from '@/utils/auth'

const BASE_URL = Settings.BASE_URL
const TIMEOUT = 60000

const instance = axios.create({
  baseURL: BASE_URL,
  timeout: TIMEOUT
})

instance.interceptors.request.use((config) => {
  nProgress.start()
  config.headers.setAuthorization(getToken())
  return config
})

instance.interceptors.response.use(
  (res) => {
    const { code, message, data } = res.data

    nProgress.done()

    switch (code) {
      case '200':
        return data
      default:
        ElMessage.error(message)
        return Promise.reject(new Error(message))
    }
  },
  (error) => {
    ElMessage.error(error.message)
    nProgress.done()

    return Promise.reject(error)
  }
)

export default instance
